/*
 * 页面主入口，负责模块拼装
 */
require( '$d/css/common.less' );
require('./style.less');
define( [
  'require',
  'jquery',
  'login',
  'header',
  'bigwe_utils',
  'message',
  'constants',
  'api',
  'login',
  'ueditor',
  'styleFilter',
  'combiner'
], function( require, $ ) {

  // 依赖注入
  var c = require( 'constants' );
  var bu = require( 'bigwe_utils' );
  var sf = require( 'styleFilter' );
  var udt = require( 'ueditor' );
  var login = require( 'login' );
  var combiner = require( 'combiner' );
  var BIGWE_API = require( 'api' );
  var ShowTitleMessage = require( 'message' );


  // 初始化样式内容
  sf.init();

  // 既存变量容错
  var md5 = bu.md5;
  var showTime = ShowTitleMessage.showTime;
  var tagsMaxCharLenth = c.tagsMaxCharLenth;

  // 添加登录成功的回调
  login.addLoginCallback( function() {

  } );

  var thisApi = BIGWE_API.TEMPLATE,
    rightCol = $( '.simplemsg_col' ),
    styleCol = $( '.style_col' ),
    editorCol = $( '.editor_col' ),
    // 初始化编辑器是否有内容
    isCreat = !0,
    // 编辑器内容是否改变了
    isContentChange = 0,
    cd = $( '#cd' ).val() + '',
    tid = $( '#tid' ).val() + '',
    submitData = {},
    keyStr = 'bigweTemplate' + $( '#frm_header #user-id-bg' ).val(),
    ed = current_editor = udt.getEditor( 'templateContent', {
      initialFrameHeight: 650,
      customtagHtml: '<div class="bodytips_outer"><span class="gray body-tips">在此输入内容</span></div>',
      toolbars: [
        [ "undo", "redo", "|", /*"paragraph", "|",*/ "fontfamily",
          "fontsize", 'blockquote', "horizontal", "|", "removeformat", 'formatmatch', "autotypeset",
          'background', 'linebreak', "|", 'spechars',
          'subscript', 'superscript', "bold",
          "italic", "underline", 'strikethrough', "forecolor", "shadowcolor", "backcolor", "|",
          "indent", "justifyleft", "justifycenter", "justifyright", 'justifyjustify',
          "rowspacingtop", 'rowspacingbottom', "lineheight", "|", 'insertorderedlist',
          'insertunorderedlist', 'emotion', 'searchreplace', 'link', 'simpleupload', 'insertimage', 'message', 'imgstyle'
        ]
      ],
      autoFloatEnabled: true,
      topOffset: 48
    } ),
    thisUtil = {
      artPreviewBody: function() {
        var content = submitData.content = this.getContent();
        $( this.body ).mediaSrcAttr();
        if ( combiner.$selector.hasClass( 'active' ) ) {
          $( "#art_preview_body", combiner.$iframe ).html( content ).mediaSrcAttr().mediaFormat();
        }
      },
      dataCheck: function() {
        if ( !submitData.content ) {
          ShowTitleMessage.showWarning( '请先输入模板内容', showTime );
          return 0;
        }
        if ( $.trim( $( '.ipt_template_title', rightCol ).val() ) == '' ) {
          ShowTitleMessage.showWarning( '模板标题不能为空哦', showTime );
          $( '.ipt_template_title', rightCol ).trigger( 'focus' );
          return 0;
        } else {
          submitData.title = $.trim( $( '.ipt_template_title', rightCol ).val() );
        }

        submitData.describe = $.trim( $( '.texta_abstract', rightCol ).val() );

        var tags = '',
          tagLen = $( '.tags_content .tag_item' ).each( function( index ) {
            tags += $( this ).text();
            if ( ( $( '.tags_content .tag_item' ).length - 1 ) != index ) {
              tags += ',';
            }
          } ).length;

        if ( !tagLen ) {
          ShowTitleMessage.showWarning( '请至少添加一个标签', showTime );
          $( '.inner_text_ipt', rightCol ).trigger( 'focus' );
          return 0;
        } else if ( tagLen > 5 ) {
          ShowTitleMessage.showWarning( '标签不能超过5个', showTime );
          return 0;
        } else {
          submitData.tags = tags;
        }
        if ( $( 'img', ed.body ).length ) {
          submitData.pic = $( 'img', ed.body ).eq( 0 ).prop( 'src' );
        }
        submitData.pic = submitData.pic ? submitData.pic : ( c.resPath + '/images/default_template_face.png' );

        return JSON.stringify( submitData ).replace( c.img02StoreRegxDomain, '' ).replace( c.img02StoreRegx, '' )
      },
      doTemplateSave: function( success, complete ) {
        var subData = thisUtil.dataCheck();
        if ( subData ) {
          subData = $.parseJSON( subData );
          ShowTitleMessage.show( '正在保存' );
          $.ajax( {
            type: 'post',
            url: thisApi.SAVE_TEMPLATE,
            data: subData,
            success: function( data ) {
              data = $.parseJSON( data );
              if ( !data.ret ) {
                if ( data.data.tid ) {
                  submitData.tid = data.data.tid;
                  ShowTitleMessage.show( '保存成功', showTime );
                  // 保存成功重置
                  isContentChange = 0;
                  thisUtil.autoSave.clear();
                  if ( $.isFunction( success ) ) {
                    success.apply( arguments );
                  }
                }
              } else {
                ShowTitleMessage.showWarning( data.msg || '保存失败，请重试', showTime );
              }
            },
            complete: function() {
              if ( $.isFunction( complete ) ) {
                complete.apply( arguments );
              }
            }
          } )
        } else {
          if ( $.isFunction( complete ) ) {
            complete();
          }
        }
      },
      charFilter: function( str ) {
        // 过滤中文数字字幕以外的字符
        return str.replace( /[^\u4e00-\u9fa5\sa-zA-Z0-9]+/g, '' )
      },
      dataFull: function( obj ) {
        $( '.ipt_template_title', rightCol ).val( obj.title || '' );
        $( '.texta_abstract', rightCol ).val( obj.describe || '' );
        creatTagHtml( ( obj.tags || '' ).split( ',' ) );
        ed.setContent( obj.content || '' );
        submitData = obj;
      },
      autoSave: {
        intervalID: '',
        storageKey: function() {

          if ( cd ) {
            return md5( keyStr + cd );
          } else if ( tid ) {
            return md5( keyStr + tid );
          } else {
            return md5( keyStr );
          }
        }(),
        start: function() {
          var _this = this;
          if ( !this.intervalID ) {
            $( '.autosave .autosave-text', editorCol ).fadeIn();
            this.intervalID = setInterval( function() {
              window.localStorage.setItem( _this.storageKey, JSON.stringify( submitData ) );
            }, 1e3 );
            return !0;
          }

          return 0;
        },
        clear: function() {
          if ( this.intervalID ) {
            clearInterval( this.intervalID );
            delete this.intervalID;
          }
          window.localStorage.removeItem( this.storageKey );
        },
        fullDataToPage: function() {
          thisUtil.dataFull( this._getLocalStorage() );
        },
        _getLocalStorage: function() {
          var thisStorage = window.localStorage.getItem( this.storageKey );
          if ( thisStorage ) {
            return $.parseJSON( thisStorage );
          }
          return undefined;
        },
        showDraftLink: function() {
          if ( this._getLocalStorage() ) {
            $( '.autosave .draft-text', editorCol ).fadeIn( 500 );
          }
        }
      }
    }
  ed.addListener( 'blur', function() {

    thisUtil.artPreviewBody.call( this );

  } );

  ed.addListener( 'contentChange', function() {

    thisUtil.artPreviewBody.call( this );
    submitData.content = this.getContent();
    if ( isCreat ) {
      thisUtil.autoSave.start();
    } else {
      if ( this.firstContentChange ) {
        thisUtil.autoSave.start();
      }
    }
    isContentChange = !0;
    this.firstContentChange = !0;
  } );

  $.extend( combiner, {
    hide: function() {
      $( 'iframe', combiner.$iframe ).removeAttr( 'src' );
    },
    show: function() {
      thisUtil.artPreviewBody.call( ed );
    }
  } );

  /***************************页面事件*******************************/

  ;
  ( function( self, ed ) {
    //  样式列

    self.keepOn( {
      datumTop: 48,
      style: {
        'height': 'auto',
        'bottom': '126px',
        'z-index': 3
      },
      reservedStyle: {
        'max-height': $( window ).height()
      },
      autoFullPlace: false
    } ).on( 'click', '.mystyle_nav li', function() {
      $( this ).addClass( 'selected' ).siblings().removeClass( 'selected' );
    } ).on( 'click', '.style_bar_control', function() {
      var toolbarbox = $( '.template_inner .edui-editor-toolbarbox' ),
        fixedBtn = $( '.fixed_btn_group .btn_group_wrap' );
      if ( editorCol.hasClass( 'active' ) ) {
        $( this ).parent().removeClass( 'active' );
        editorCol.removeClass( 'active' );
        if ( toolbarbox.css( 'position' ) == 'fixed' ) {
          toolbarbox.css( {
            width: 518
          } );
        }
        fixedBtn.removeClass( 'active' );
      } else {
        $( this ).parent().addClass( 'active' );
        editorCol.addClass( 'active' );
        fixedBtn.addClass( 'active' );
        if ( toolbarbox.css( 'position' ) == 'fixed' ) {
          toolbarbox.css( {
            width: 813
          } );
        }
      }
    } ).css( {
      'max-height': $( window ).height()
    } );
    $( '.style_columns', self ).bwColumns( [ '素材样式' /*, '我的样式'*/ ], function( index ) {
      var animateTarget = $( '.style_type_container', self );
      if ( animateTarget.hasClass( 'active' ) ) {
        animateTarget.removeClass( 'active' );
      } else {
        animateTarget.addClass( 'active' );
      }
    } );

    $( '.template_inner .template_title' ).keepOn( {
      style: {
        'z-index': 5
      },
      autoFullPlace: false
    } );

    $( '.editor_col' ).on( 'click', '.autosave .draft-text', function() {
      thisUtil.autoSave.fullDataToPage();
    } );

  }( styleCol, current_editor ) );



  $( '.fixed_btn_group' ).on( 'click', '.save_template', function() {
    var _this = $( this );
    _this.prop( 'disabled', 'disabled' );
    thisUtil.doTemplateSave( callback, callback );

    function callback() {
      _this.removeAttr( 'disabled' );
    }
  } ).on( 'click', '.save_use', function() {
    var _this = $( this );
    _this.prop( 'disabled', 'disabled' );
    thisUtil.doTemplateSave( function() {
      window.location.href = '/edit_text?edit_type=1&template_id=' + submitData.tid;
    }, function() {
      _this.removeAttr( 'disabled' );
    } );
  } ).on( 'click', '.preview_template', function( e ) {
    e.stopPropagation();
    $( '.phone-preview', combiner.$selector ).trigger( 'click' );
  } );

  rightCol.keepOn( {
    datumTop: 48,
    autoFullPlace: false
  } ).on( {
    blur: function() {
      creatTag.call( this );
    },
    keydown: function( e ) {
      e = e || event;
      if ( e.keyCode == 13 || e.keyCode == 188 ) {
        creatTag.call( this );
        return false;
      }
    }

  }, '.inner_text_ipt' ).on( 'click', '.tags_content .tag_item', function() {

    $( this ).remove();

  } ).on( 'change', '.ipt_template_title', function() {
    submitData.title = $( this ).val();
    thisUtil.autoSave.start();
  } ).on( 'change', '.texta_abstract', function() {
    submitData.describe = $( this ).val();
    thisUtil.autoSave.start();
  } );

  function creatTag() {
    var tag = $.trim( $( this ).val() ),
      subTag = '';

    if ( tag ) {
      tag = tag.cutStringByte( tagsMaxCharLenth ).replace( /[^\u4e00-\u9fa5\sa-zA-Z0-9]+/g, '' ),
        isSameTag = 0;

      var tagLen = $( '.tags_content .tag_item', rightCol ).each( function( index ) {
        var thisTag = $( this ).text();
        if ( index ) {
          tagStr += ',' + thisTag;
        } else {
          tagStr += thisTag;
        }
        if ( tag == thisTag ) {
          ShowTitleMessage.showWarning( '已存在相同标签', showTime );
          isSameTag = !0;
          return false;
        }
      } ).length;
      if ( tagLen >= 5 ) {
        ShowTitleMessage.showWarning( '最多输入5个标签，请先删除多余的标签再添加', showTime );
      } else {
        if ( !isSameTag ) {

          creatTagHtml( [ tag ] );
          var tagStr = ''
          $( '.tags_content .tag_item', rightCol ).each( function( index ) {
            var thisTag = $( this ).text();
            if ( index ) {
              tagStr += ',' + thisTag;
            } else {
              tagStr += thisTag;
            }
          } );
          submitData.tags = tagStr;
          thisUtil.autoSave.start();
          $( this ).val( '' );
        }
      }
    }
  }

  function creatTagHtml( array ) {
    var html = '';
    for ( i in array ) {
      if ( array[ i ] ) {
        html += '<span class="tag_item" title="' + array[ i ] + '">' + array[ i ] + '</span>';
      }
    }
    $( '.tags_content', rightCol ).append( html );
  }

  window.onbeforeunload = function( event ) {
    if ( isContentChange ) {
      return '即将离开页面，请确认您编辑的内容已经保存';
    }
  }


  /***************************页面事件end*******************************/


  // 拉取编辑数据
  ;
  ( function() {

    var editorDtd = $.Deferred(),
      promiseParam = [ editorReady( editorDtd ) ];

    function editorReady( dtd ) {

      ed.ready( function() {
        thisUtil.autoSave.showDraftLink();
        // 该异步对象完成
        dtd.resolve();
      } );
      // 承诺的，外部无法改变其状态
      return dtd.promise();
    }
    if ( cd && tid ) {
      ShowTitleMessage.showWarning( '参数错误，新建模板模式', showTime );
    } else {

      if ( cd ) {
        isCreat = 0;
        ShowTitleMessage.show( '正在获取模板信息' );
        promiseParam.push( $.ajax( {
          url: thisApi.CREATE_TEMPLATE,
          data: {
            pcode: cd
          }
        } ) );
      } else if ( tid ) {
        isCreat = 0;
        ShowTitleMessage.show( '正在获取模板信息' );
        promiseParam.push( $.ajax( {
          url: thisApi.GET_TEMPLATE,
          data: {
            tid: tid
          }
        } ) );
      }

    }

    $.when.apply( $, promiseParam ).then( function( arg, arg2 ) {
      // 取得响应对象，为数组的第一个下标 response
      var repData = arg2 ? arg2[ 0 ] : '';
      if ( repData ) {
        ShowTitleMessage.hide();
        response = JSON.parse( repData );
        if ( !response.ret ) {
          thisUtil.dataFull( response.data || {} );
          isContentChange = 0;
        } else {
          ShowTitleMessage.showWarning( response.msg || '发生错误', showTime );
        }
      }

    } ).fail( function() {

    } );

  }() );

} );
